<template>
  <div class="container">
    <div class="app-container">
      <el-button
        size="mini"
        type="primary"
        class="btn-add"
        @click="addPermission(1, 0)"
        >添加权限</el-button
      >
      <el-table
        :data="tableData"
        style="width: 100%"
        row-key="id"
        default-expand-all
      >
        <el-table-column prop="name" label="名称" />
        <el-table-column prop="code" label="标识" />
        <el-table-column prop="description" label="描述" />
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <el-button
              v-if="row.type === 1"
              size="mini"
              type="text"
              @click="addPermission(2, row.id)"
              >添加</el-button
            >
            <el-button size="mini" type="text" @click="alterPermission(row.id)"
              >编辑</el-button
            >
            <el-popconfirm
              title="这是一段内容确定删除吗？"
              @onConfirm="deleteRole(row.id)"
            >
              <el-button
                slot="reference"
                size="mini"
                type="text"
                style="margin-left: 10px"
                >删除</el-button
              >
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog
      :visible.sync="dialogVisible"
      title="添加权限"
      width="30%"
      @close="handleClose"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="权限名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="权限标识" prop="code">
          <el-input v-model="form.code" />
        </el-form-item>
        <el-form-item label="权限描述" prop="description">
          <el-input v-model="form.description" />
        </el-form-item>
        <el-form-item label="开启" prop="enVisible">
          <el-switch
            v-model="form.enVisible"
            active-value="1"
            inactive-value="0"
          />
        </el-form-item>
        <div class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import {
  getPermissionList,
  addPermission,
  updatePermission,
  getPermissionDetail,
  delPermission
} from '@/api/permission'
import { transListToTreeData } from '@/utils'
export default {
  name: 'Permission',
  data() {
    const validateName = (rule, value, callback) => {
      if (!value) {
        callback(new Error('权限名称不能为空'))
      } else if (this.existingNames.includes(value)) {
        callback(new Error('权限名称不能重名'))
      } else {
        callback()
      }
    }
    const validateCode = (rule, value, callback) => {
      if (!value) {
        callback(new Error('权限标识不能为空'))
      } else if (this.existingCode.includes(value)) {
        callback(new Error('权限标识不能重名'))
      } else {
        callback()
      }
    }

    return {
      tableData: [],
      dialogVisible: false, // 控制新增/编辑弹窗
      form: {
        name: '',
        code: '',
        description: '',
        enVisible: '0',
        type: '',
        pid: ''
      },
      rules: {
        name: [{ validator: validateName, trigger: 'blur' }],
        code: [{ validator: validateCode, trigger: 'blur' }]
      },
      existingNames: [], // 存储已存在的权限名称
      existingCodes: [] // 存储已存在的权限标识
    }
  },
  created() {
    this.getPermissionList()
  },
  methods: {
    async getPermissionList() {
      const res = await getPermissionList()
      this.tableData = transListToTreeData(res, 0)
      if (this.form.id) {
        const resx = res.filter(item => item.id !== this.form.id)
        // 获取已存在的权限名称和标识
        this.existingNames = resx.map(item => item.name)
        this.existingCode = resx.map(item => item.code)
      } else {
        // 获取已存在的权限名称和标识
        this.existingNames = res.map(item => item.name)
        this.existingCode = res.map(item => item.code)
      }
    },
    handleClose() {
      // 重置表单
      this.form = {
        name: '',
        code: '',
        description: '',
        enVisible: '0',
        type: '',
        pid: ''
      }
      this.dialogVisible = false
    },
    handleSubmit() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          if (this.form.id) {
            // 更新权限逻辑
            await updatePermission(this.form)
            // 弹出提示
            this.$message.success('更新成功')
          } else {
            // 提交表单逻辑
            await addPermission(this.form)
            // 弹出提示
            this.$message.success('添加成功')
          }
          // 刷新列表
          this.getPermissionList()
          this.handleClose()
        } else {
          console.log('表单验证失败')
          return false
        }
      })
    },
    // 新增权限
    async addPermission(type, pid) {
      this.form.type = type
      this.form.pid = pid
      this.dialogVisible = true
    },
    // 编辑权限
    async alterPermission(id) {
      this.form = await getPermissionDetail(id)
      const res = await getPermissionList()
      if (this.form.id) {
        const resx = res.filter(item => item.id !== this.form.id)
        // 获取已存在的权限名称和标识
        this.existingNames = resx.map(item => item.name)
        this.existingCode = resx.map(item => item.code)
      } else {
        // 获取已存在的权限名称和标识
        this.existingNames = res.map(item => item.name)
        this.existingCode = res.map(item => item.code)
      }
      this.dialogVisible = true
    },
    // 删除权限
    async deleteRole(id) {
      await delPermission(id)
      this.getPermissionList()
      this.$message.success('删除成功')
    }
  }
}
</script>

<style scoped>
.btn-add {
  margin: 10px;
}
.dialog-footer {
  text-align: center;
}
</style>
